<template>
  <div class="order-list animate__animated animate__fadeIn">
    <el-card shadow="never">
      <!-- 搜索区域 -->
      <div class="search-area">
        <div class="card-header">
          <el-form :inline="true" class="form-inline">
            <el-form-item label="订单编号">
              <el-input
                v-model="searchForm.orderNum"
                placeholder="请输入订单编号"
                clearable
                @keyup.enter="handleSearch"
              />
            </el-form-item>
            <el-form-item label="物流状态">
              <el-select
                v-model="searchForm.status"
                placeholder="请选择状态"
                clearable
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="handleSearch"
                :loading="loading"
              >
                <el-icon><Search /></el-icon>
                查询
              </el-button>
              <el-button @click="resetSearch">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 表格区域 -->
      <el-table
        :data="orderList"
        style="width: 100%"
        v-loading="loading"
        border
        stripe
        max-height="600"
        :scrollbar-always-on="true"
      >
        <el-table-column prop="orderNum" label="订单编号" width="180" show-overflow-tooltip />
        <el-table-column prop="userId" label="用户ID" width="100" show-overflow-tooltip />
        <el-table-column prop="total" label="总金额" width="120">
          <template #default="{ row }">
            <span class="price">¥{{ row.total || 0.00 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="商品数量" width="100">
          <template #default="{ row }"> {{ row.amount || 0 }}件 </template>
        </el-table-column>
        <el-table-column prop="method" label="支付方式" width="120">
          <template #default="{ row }">
            {{ paymentMethods[row.method] || row.method || "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="Logistics_status" label="物流状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.Logistics_status)" size="small">
              {{ getStatusText(row.Logistics_status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="收货人" width="100" show-overflow-tooltip />
        <el-table-column prop="phone" label="联系电话" width="130" show-overflow-tooltip />
        <el-table-column
          prop="address"
          label="收货地址"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column prop="orderTime" label="下单时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.orderTime) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="90">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              @click="viewDetail(row)"
              :loading="loading"
            >
              查看详情
            </el-button>
            <el-button
              type="warning"
              link
              @click="handleEditStatus(row)"
              v-if="canEditStatus(row.Logistics_status)"
              :loading="loading"
            >
              修改状态
            </el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete(row)"
              v-if="canDelete(row.Logistics_status)"
              :loading="loading"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>

  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { getAllOrders, updateOrderStatus, deleteOrder } from "../../api/order";

const router = useRouter();

// 数据
const orderList = ref([]);
const loading = ref(false);
const statusLoading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const statusDialogVisible = ref(false);
const currentOrder = ref({});
const statusForm = ref({
  orderNum: "",
  status: "",
  remark: "",
});

// 搜索表单
const searchForm = ref({
  orderNum: "",
  status: "",
});

// 支付方式映射
const paymentMethods = {
  1: "微信支付",
  2: "支付宝",
  3: "银行卡",
};

// 状态选项
const statusOptions = [
  { value: "0", label: "待支付" },
  { value: "1", label: "已支付" },
  { value: "2", label: "已发货" },
  { value: "3", label: "已完成" },
  { value: "4", label: "已取消" },
];

// 获取订单列表
const fetchOrders = async () => {
  try {
    loading.value = true;
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm.value,
    };
    
    console.log('请求参数:', params); // 调试日志
    
    const response = await getAllOrders(params);
    console.log('API响应:', response); // 调试日志
    
    if (response && response.status === 0) {
      if (Array.isArray(response.data.list)) {
        orderList.value = response.data.list;
      } else if (Array.isArray(response.data)) {
        // 兼容直接返回数组的情况
        orderList.value = response.data;
        total.value = response.data.length;
      } else {
        orderList.value = [];
        ElMessage.warning('返回的订单数据格式不正确');
      }
      
      // 设置总数
      if (typeof response.data.total === 'number') {
        total.value = response.data.total;
      }
    } else {
      ElMessage.error(response?.message || '获取订单列表失败');
      orderList.value = [];
    }
  } catch (error) {
    console.error('获取订单列表错误:', error);
    ElMessage.error(error.message || "获取订单列表失败");
    orderList.value = [];
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchOrders();
};

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    orderNum: "",
    status: "",
  };
  handleSearch();
};

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchOrders();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchOrders();
};

// 格式化时间
const formatTime = (time) => {
  if (!time) return "";
  try {
    const date = new Date(time);
    return date
      .toLocaleString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
      })
      .replace(/\//g, "-");
  } catch (e) {
    console.error("时间格式化错误:", e);
    return time;
  }
};

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    0: "待支付",
    1: "已支付",
    2: "已发货",
    3: "已完成",
    4: "已取消",
  };
  return map[status] || "未知状态";
};

// 获取状态标签类型
const getStatusTag = (status) => {
  const map = {
    0: "warning",
    1: "success",
    2: "primary",
    3: "info",
    4: "danger",
  };
  return map[status] || "";
};

// 获取下一步可选状态
const getNextStatusOptions = (currentStatus) => {
  const options = [];

  if (currentStatus === "0") {
    options.push({ value: "1", label: "已支付" });
    options.push({ value: "4", label: "已取消" });
  } else if (currentStatus === "1") {
    options.push({ value: "2", label: "已发货" });
    options.push({ value: "4", label: "已取消" });
  } else if (currentStatus === "2") {
    options.push({ value: "3", label: "已完成" });
  }

  return options;
};

// 判断是否可以编辑状态
const canEditStatus = (status) => {
  return getNextStatusOptions(status).length > 0;
};

// 判断是否可以删除
const canDelete = (status) => {
  return ["0", "4"].includes(status);
};

// 查看详情
const viewDetail = (row) => {
  router.push({
    name: "OrderDetail",
    params: { id: row.orderNum },
  });
};

// 修改状态
const handleEditStatus = (row) => {
  currentOrder.value = row;
  statusForm.value = {
    orderNum: row.orderNum,
    status: getNextStatusOptions(row.Logistics_status)[0]?.value || "",
    remark: "",
  };
  statusDialogVisible.value = true;
};

// 确认修改状态
const confirmStatusChange = async () => {
  try {
    statusLoading.value = true;
    const requestData = {
      orderNum: statusForm.value.orderNum,
      Logistics_status: statusForm.value.status,
    };
    await updateOrderStatus(requestData);
    ElMessage.success("状态更新成功");
    statusDialogVisible.value = false;
    fetchOrders();
  } catch (error) {
    ElMessage.error(error.message || "状态更新失败");
  } finally {
    statusLoading.value = false;
  }
};

// 删除订单
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除订单 ${row.orderNum} 吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      loading.value = true;
      await deleteOrder(row.orderNum);
      ElMessage.success("删除订单成功");
      if (orderList.value.length === 1 && currentPage.value > 1) {
        currentPage.value--;
      }
      fetchOrders();
    } catch (error) {
      ElMessage.error(error.message || "删除订单失败");
    } finally {
      loading.value = false;
    }
  });
};

onMounted(() => {
  fetchOrders();
});
</script>

<style scoped>
.order-list {
  padding: 20px;
  min-height: calc(100vh - 40px);
  background-color: #f5f7fa;
}

.search-area {
  margin-bottom: 20px;
}

.form-inline {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}
</style>